package com.tyx.chargingpile.job;

import com.alibaba.fastjson.JSONObject;
import com.tyx.chargingpile.pojo.ChargingRecord;
import com.tyx.chargingpile.service.ChargingRecordService;
import com.tyx.chargingpile.service.HttpAPIService;
import com.tyx.chargingpile.util.Util;
import com.tyx.chargingpile.vo.HttpResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 充电记录上报定时器，定时给后台推送
 */
@Component
@Configuration
@EnableScheduling
public class RecordJob {
    private final static Logger LOGGER = LoggerFactory.getLogger(RecordJob.class);
    @Value("${chargingback.url}")
    private String url;
    @Autowired
    HttpAPIService httpAPIService;
    @Autowired
    private ChargingRecordService chargingRecordService;

    @Scheduled(cron = "0 0 0/1 * * ? ")
    private void configureTasks() {
        LOGGER.info("开始充电记录上报定时器.....");
        List<String> sendStatusIn = new ArrayList<>();
        sendStatusIn.add("0"); // 未推送
        sendStatusIn.add("2"); // 推送失败
        List<ChargingRecord> chargingRecordList = chargingRecordService.findBySendStatusIn(sendStatusIn);
        List<ChargingRecord> recordList = new ArrayList<>();
        for (ChargingRecord chargingRecord:
             chargingRecordList) {
            boolean result = sendChargingRecord(chargingRecord);
            if (result){
                if (result){
                    chargingRecord.setSendStatus("1");
                    LOGGER.info("结束充电记录上报定时器.....订单号" + chargingRecord.getOrderNum() + "推送成功");
                }else {
                    chargingRecord.setSendStatus("2");
                    LOGGER.info("结束充电记录上报定时器.....订单号" + chargingRecord.getOrderNum() + "推送失败");
                }
            }
            recordList.add(chargingRecord);
        }
        chargingRecordService.saveOrUpdate(recordList);
        LOGGER.info("结束充电记录上报定时器.....");
    }

    /**
     * 请求后台，推送充电记录
     * @param chargingRecord
     * @return
     * @throws Exception
     */
    private boolean sendChargingRecord(ChargingRecord chargingRecord){
        try {
            JSONObject requestJson = new JSONObject();
            JSONObject dataJson = new JSONObject();
            // 电桩编号，去掉首位
            String deviceId = chargingRecord.getPileNum().substring(1,chargingRecord.getPileNum().length());
            // 枪口编号，hex码转成int
            byte[] gunPointNumData = Util.String2BCD(chargingRecord.getGunpointNum());
            String ChargePortIndex = Util.HexToint(gunPointNumData,gunPointNumData.length) + "";
            // 消费电量，保留小数点后2位
            String electric = Double.parseDouble(chargingRecord.getConsumeElectric()) / 100 + "";
            // 消费金额
            String amountMoney = Double.parseDouble(chargingRecord.getConsumeMoney()) / 100 + "";
            // 开始SOC
            String startSocHexStr = chargingRecord.getStartEndSoc().substring(0,2);
            byte[] startSocHex = Util.String2BCD(startSocHexStr);
            String startSoc = Util.HexToint(startSocHex,startSocHex.length) + "";
            //结束SOC
            String endSocHexStr = chargingRecord.getStartEndSoc().substring(2,chargingRecord.getStartEndSoc().length());
            byte[] endSocHex = Util.String2BCD(endSocHexStr);
            String endSoc = Util.HexToint(endSocHex,endSocHex.length) + "";
            // 开始时间
            String startTime = chargingRecord.getStartEndTime().substring(0,12);
            // 结束时间
            String endTime = chargingRecord.getStartEndTime().substring(12,chargingRecord.getStartEndTime().length());
            // 枪口使用次数
            byte[] usageCountHex = Util.String2BCD(chargingRecord.getGunUseCount());
            String usageCount = Util.HexToint(usageCountHex,usageCountHex.length) + "";
            dataJson.put("DeviceId",deviceId);
            dataJson.put("ChargePortIndex",ChargePortIndex);
            dataJson.put("OrderId",chargingRecord.getOrderNum());
            dataJson.put("CardId",chargingRecord.getCardNo());
            dataJson.put("Electric",electric);
            dataJson.put("AmountMoney",amountMoney);
            dataJson.put("BeginSOC",startSoc);
            dataJson.put("EndSOC",endSoc);
            dataJson.put("BeginTime",startTime);
            dataJson.put("EndTime",endTime);
            dataJson.put("OrderResult",chargingRecord.getOrderFinishReason());
            dataJson.put("UsageCount",usageCount);
            dataJson.put("VINCode",chargingRecord.getVinCode());
            requestJson.put("MainCMD",68);
            requestJson.put("SubCMD",4);
            requestJson.put("Data",dataJson);
            LOGGER.info("充电记录上报定时器--充电记录推送至后台：" + requestJson.toJSONString());
            HttpResult result = httpAPIService.doPost2Json(url,requestJson.toJSONString());
            if(result.getCode() != 200){
                LOGGER.info("充电记录上报定时器--充电记录推送至后台：false");
                return false;
            }
            LOGGER.info("充电记录上报定时器--充电记录推送至后台：true");
            return true;
        } catch (Exception e){
            e.printStackTrace();
            LOGGER.info("充电记录上报定时器--充电记录推送至后台: 报错" + e.getMessage());
            return false;
        }
    }
}
